package com.songyz.image.compress.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
import org.springframework.web.socket.messaging.SessionUnsubscribeEvent;

import com.songyz.image.compress.utils.JSONHelper;

/**
 * WebSocket客户端状态监听
 * 
 * @author songyz
 * @createTime 2023-03-19 19:02:47
 */
@Component
public class WebSocketEventListener {

    private static Logger log = LoggerFactory.getLogger(WebSocketEventListener.class);

    /**
     * 监听客户端连接
     *
     * @param event 连接事件对象
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        log.info("WebSocket客户端已连接,headers:{}", JSONHelper.toJSON(event.getMessage().getHeaders()));
    }

    /**
     * 监听客户端关闭事件
     *
     * @param event 关闭事件对象
     */
    @EventListener
    public void handleWebSocketCloseListener(SessionDisconnectEvent event) {
        log.info("WebSocket客户端已关闭,headers:{}", JSONHelper.toJSON(event.getMessage().getHeaders()));
    }

    /**
     * 监听客户端订阅事件
     *
     * @param event 订阅事件对象
     */
    @EventListener
    public void handleSubscription(SessionSubscribeEvent event) {
        log.info("WebSocket客户端已订阅,,订阅节点:{}", event.getMessage().getHeaders().get("simpDestination"));
    }

    /**
     * 监听客户端取消订阅事件
     *
     * @param event 取消订阅事件对象
     */
    @EventListener
    public void handleUnSubscription(SessionUnsubscribeEvent event) {
        log.info("WebSocket客户端已取消订阅,取消订阅节点:{}", event.getMessage().getHeaders().get("simpDestination"));
    }
}
